import Icon from '@/components/icon'
import { useInitState } from '@/hooks'
import { getUserChannelAction } from '@/store/actions/home'
import { setActive } from '@/store/modules/home'
import { Popup, Tabs } from 'antd-mobile'
import { useState } from 'react'
import { useDispatch } from 'react-redux'
// 导入频道管理组件
import Channels from './components/Channels'
// 导入频道新闻列表
import ArticleList from './components/ArticleList'

import styles from './index.module.scss'
import { useNavigate } from 'react-router-dom'

const Home = () => {
  const nav = useNavigate()
  const dispatch = useDispatch()
  // 1. 获取用户频道数据 || 当前点击频道ID
  const { userChannel, active } = useInitState(getUserChannelAction, 'home')
  // 2. 控制频道管理弹层显隐
  const [showChannel, setShowChannel] = useState(false)
  // 3. 我的频道高亮联动
  const changeActive = (id: string) => {
    console.log(typeof id, id)
    dispatch(setActive(parseInt(id)))
  }

  return (
    <div className={styles.root}>
      {/* 1. 频道 Tabs 列表 */}
      {/* activeLineMode控制高亮的下滑线展现样式 => fixed 固定宽度 */}
      {userChannel.length > 0 && (
        <Tabs
          activeKey={active + ''}
          onChange={changeActive}
          className="tabs"
          activeLineMode="auto"
        >
          {userChannel.map((item, i) => (
            <Tabs.Tab title={item.name} key={item.id}>
              {/* 当前频道新闻列表 */}
              <ArticleList channelId={item.id} />
            </Tabs.Tab>
          ))}
        </Tabs>
      )}
      {/* 右上角图标 */}
      <div className="tabs-opration">
        {/* 搜索 */}
        <Icon
          onClick={() => {
            nav('/search')
          }}
          type="iconbtn_search"
        />
        {/* 管理频道 */}
        <Icon
          onClick={() => {
            setShowChannel(true)
          }}
          type="iconbtn_channel"
        />
      </div>

      {/* 频道管理弹层 */}
      <Popup className="channel-popup" visible={showChannel} position="left">
        <Channels onClose={setShowChannel} />
      </Popup>
    </div>
  )
}

export default Home
